package com.tools.xxf.updatelib.apkinfo.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.google.gson.Gson;
import com.tools.xxf.updatelib.R;
import com.tools.xxf.updatelib.apkinfo.ApkInFoBean;
import com.tools.xxf.updatelib.apkinfo.ShareNewApk;
import com.tools.xxf.updatelib.updateapp.ConfigType;
import com.tools.xxf.updatelib.updateapp.UpdateMode;
import com.tools.xxf.updatelib.updateapp.UpdateService;
import com.tools.xxf.updatelib.updateapp.fragment.UpdateFile;

import java.util.WeakHashMap;

/**
 * TODO
 *
 * @author XXF
 *         Create Time : 2017/11/7 18:05
 */
public class GetServerApkFragment extends Fragment implements UpdatePresenter.UpdateCall {

    private static final String UPDATE_MODEL = "mode";
    private static final String UPDATE_VERSION = "version";
    private UpdateMode mode;
    private String version;
    private UpdateFinish activity;
    private ProgressDialog dialog;
    private AlertDialog alertDialog;


    public static GetServerApkFragment.Builder create() {
        return new GetServerApkFragment.Builder();
    }

    public static class Builder {
        private GetServerApkFragment updateFragment;
        private final WeakHashMap<String, Object> UPDATE_CONFIGS = new WeakHashMap<>();

        private Builder() {
            UPDATE_CONFIGS.put(ConfigType.CONFIG_READY.name(), false);
        }

        public Builder bindModel(UpdateMode mode) {
            UPDATE_CONFIGS.put(ConfigType.LOAD_MODEL.name(), mode);
            UPDATE_CONFIGS.put(ConfigType.CONFIG_READY.name(), true);
            return this;
        }

        /**
         * @param version debug 、develop、release 。
         */
        public Builder versionMode(String version) {
            UPDATE_CONFIGS.put(ConfigType.LOAD_VERSION.name(), version);
            return this;
        }

        private Builder checkConfiguration() {
            final boolean isReady = (boolean) UPDATE_CONFIGS.get(ConfigType.CONFIG_READY.name());
            if (!isReady) {
                throw new RuntimeException("Configuration is not ready,call build method");
            }
            return this;
        }

        @SuppressWarnings({"unchecked"})
        final <T> T getConfigurations(Enum<ConfigType> key) {
            checkConfiguration();
            return (T) UPDATE_CONFIGS.get(key.name());
        }

        public GetServerApkFragment build(FragmentManager manager) {
            if (manager == null) {
                throw new NullPointerException("manager == null");
            }
            UpdateMode mode = getConfigurations(ConfigType.LOAD_MODEL);
            String version = getConfigurations(ConfigType.LOAD_VERSION) + "";
            if (null == updateFragment)
                updateFragment = newInstance(mode, version);
            updateFragment.show(manager);

            return updateFragment;
        }
    }


    private static GetServerApkFragment newInstance(UpdateMode mode, String version) {
        Bundle args = new Bundle();
        GetServerApkFragment fragment = new GetServerApkFragment();
        args.putSerializable(UPDATE_MODEL, mode);
        args.putString(UPDATE_VERSION, version);
        fragment.setArguments(args);
        return fragment;
    }

    public void show(FragmentManager manager) {
        FragmentTransaction ft = manager.beginTransaction();
        ft.add(this, "GetServerApkFragment");
        ft.commit();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity = (UpdateFinish) context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mode = (UpdateMode) getArguments().getSerializable(UPDATE_MODEL);
        version = getArguments().getString(UPDATE_VERSION);
        if (TextUtils.isEmpty(version))
            version = "debug";
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
            Bundle savedInstanceState) {

        if (mode == UpdateMode.UNFORCE) {
            if (UpdateService.isLoading) {

                AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
                alertDialog
                        .setMessage(R.string.update_app_model_tips)
                        .setPositiveButton("YES", null).show();
                return super.onCreateView(inflater, container, savedInstanceState);
            } else {
                if (dialog == null) {
                    dialog = new ProgressDialog(getActivity());
                    dialog.setMessage("loading ...");
                    dialog.show();
                }
            }
        }

        //xxf  添加服务器apk信息获取方法
        UpdatePresenter.getInstance().getToken(version, this,"com.ocean.motube"/* getActivity().getPackageName()*/);

        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void getTokenFail(Throwable e) {
        LogUtils.d(new Gson().toJson(e));
        if (activity != null) {
            activity.updateFinish();
        }
        if (dialog != null && dialog.isShowing()) {
            dialog.hide();
        }
        if (getActivity() != null) {

            if (!NetworkUtils.isConnected()) {
                Toast.makeText(getActivity(), R.string.no_net, Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getActivity(), R.string.server_error, Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    public void getAPKinfoFail(Throwable e) {
        LogUtils.d(new Gson().toJson(e));
        if (activity != null) {
            activity.updateFinish();
        }
        if (dialog != null && dialog.isShowing()) {
            dialog.hide();
        }
        if (getActivity() != null) {
            if (!NetworkUtils.isConnected()) {
                Toast.makeText(getActivity(), R.string.no_net, Toast.LENGTH_LONG).show();
            } else {
                if (!TextUtils.isEmpty(e.getMessage()))
                    Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG).show();
                else
                    Toast.makeText(getActivity(), R.string.server_error, Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    public void getAPKinfoSuccessful(ApkInFoBean bean) {
        if (dialog != null && dialog.isShowing()) {
            dialog.hide();
        }
        LogUtils.d(new Gson().toJson(bean));
        int XX = 0;
        int localXX = 0;
        int versionCode = 0;
        int localVersionCode = AppUtils.getAppVersionCode();
        String localVersionName = AppUtils.getAppVersionName();
        try {
            XX = Integer.parseInt(bean.getData().getVersionName().split("\\.")[0]);
            localXX = Integer.parseInt(localVersionName.split("\\.")[0]);
            versionCode = bean.getData().getVersionCode();

        } catch (NumberFormatException e) {
            e.printStackTrace();
            Toast.makeText(getActivity(), R.string.server_name_error,
                    Toast.LENGTH_LONG).show();
            if (activity != null) {
                activity.updateFinish();
            }
            clear();
            return;
        } finally {//数据获取成功走这里,保存服务器最新版本信息,
            ShareNewApk share = new ShareNewApk(getActivity());
            share.saveBean(bean);
        }
        versionCode = 3;
           XX=2;
        switch (mode) {
            case UNFORCE://非绑定,从设置页面传递过来的

                if (versionCode > localVersionCode) {//小版本更新
                    startUpdate(bean);
                    return;
                } else {
                    Toast.makeText(getActivity(), "It's the latest version ", Toast.LENGTH_SHORT)
                            .show();
                }

                break;
            case FORCE://绑定,从起始页面传递过来的

                if (versionCode > localVersionCode && XX > localXX &&
                        !TextUtils.isEmpty(bean.getData().getUrl())) {//大版本强制更新
                    startUpdate(bean);
                    return;
                }

                break;
            default:
                break;
        }
        if (activity != null) {
            activity.updateFinish();
            clear();
        }
    }

    /**
     * 开启更新
     *
     * @param bean
     */
    private void startUpdate(final ApkInFoBean bean) {
        if (getActivity() == null) {
            return;
        }
        if (!NetworkUtils.isConnected()) {
            Toast.makeText(getActivity(), R.string.no_net, Toast.LENGTH_LONG).show();
        }
        if (!NetworkUtils.isWifiConnected()) {
            alertDialog = new AlertDialog.Builder(getActivity()).setMessage(R.string
                    .no_wify_update)
                    .setPositiveButton("YES", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            loadApk(bean);
                        }
                    })
                    .setNegativeButton("NO", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (activity != null) {
                                activity.updateFinish();
                            }
                        }
                    })
                    .setCancelable(false)
                    .show();
        } else {
            loadApk(bean);
        }
    }

    private void loadApk(ApkInFoBean bean) {
        UpdateFile.
                create(bean.getData().getUrl() + "&" + bean.getData().getAppName()).
                bindModel(mode).
                build(getChildFragmentManager());
    }

    public interface UpdateFinish {
        void updateFinish();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        clear();
    }

    private void clear() {
        if (alertDialog != null) {
            alertDialog.dismiss();
            alertDialog = null;
        }

        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }
}
